package com.apop.hrss.home;

import com.apop.common.config.AppConfig;
import com.apop.common.exception.ErrorCode;
import com.apop.common.model.Result;
import com.apop.common.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 业务经办相关接口
 * BizController.java
 * author: Weijie Lin
 * Date: 2021/11/9  15:23
 * Describe:失业登记插入接口
 */
@RestController
@Slf4j
@Transactional(rollbackFor = Exception.class)
@RequestMapping("/hrss")
public class BizController {

    @Resource
    AppConfig configProperties;

    /**
     * 临时文件上传接口
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file ,String formId) {
        String path = configProperties.getUploadPath();
        if (file.isEmpty()) {
            return Result.fail(new ErrorCode(500,"文件不能为空"));
        }
        if (formId == null){
            return Result.fail(new ErrorCode(500,"文件ID不能为空"));
        }
        String fileName = file.getOriginalFilename();
        List<File> files = FileUtil.getListFiles(path+formId+"/");
        for (File file1 : files) {
            if (file1.getName().equals(fileName)){
                return Result.fail(new ErrorCode(500,"文件已存在"));
            }
        }
        File dis = new File(path+formId+"/");
        if(!dis.exists()){
            dis.mkdirs();
        }

        File dest = new File(path+formId+"/" + fileName);
        try {
            file.transferTo(dest);
            log.info("上传成功");
            return Result.success(fileName);
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return Result.fail(new ErrorCode(500,"上传失败"));
    }


}
